// 模拟API服务，用于处理与后端的交互
class ApiService {
  constructor() {
    // 模拟API基础URL
    this.baseUrl = '/api';
    // 模拟网络延迟
    this.delay = 300;
  }
  
  // 模拟异步请求
  async request(method, endpoint, data = null) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        try {
          // 模拟API调用
          const url = `${this.baseUrl}${endpoint}`;
          console.log(`[API] ${method} ${url}`, data);
          
          // 模拟成功响应
          // 在实际应用中，这里应该是真实的API调用
          resolve({
            success: true,
            data: this.mockResponse(method, endpoint, data)
          });
        } catch (error) {
          // 模拟错误响应
          reject({
            success: false,
            error: error.message || '服务器错误'
          });
        }
      }, this.delay);
    });
  }
  
  // 模拟响应数据
  mockResponse(method, endpoint, data) {
    // 模拟产品相关API响应
    if (endpoint.startsWith('/products')) {
      if (method === 'GET') {
        // 获取产品列表或单个产品
        const productId = endpoint.split('/').pop();
        if (!isNaN(productId)) {
          // 返回单个产品
          return this.mockSingleProduct(parseInt(productId));
        } else {
          // 返回产品列表
          return this.mockProductList();
        }
      } else if (method === 'POST') {
        // 添加产品
        return { id: Date.now(), ...data };
      } else if (method === 'PUT') {
        // 更新产品
        const productId = endpoint.split('/').pop();
        return { id: parseInt(productId), ...data };
      } else if (method === 'DELETE') {
        // 删除产品
        return { success: true };
      }
    }
    
    // 模拟订单相关API响应
    if (endpoint.startsWith('/orders')) {
      if (method === 'GET') {
        // 获取订单列表或单个订单
        const orderId = endpoint.split('/').pop();
        if (!isNaN(orderId)) {
          // 返回单个订单
          return this.mockSingleOrder(parseInt(orderId));
        } else {
          // 返回订单列表
          return this.mockOrderList();
        }
      } else if (method === 'POST') {
        // 添加新订单
        return { id: Date.now(), ...data };
      } else if (method === 'PUT') {
        if (endpoint.includes('/status')) {
          // 更新订单状态
          const orderId = endpoint.split('/')[2];
          return { id: parseInt(orderId), status: data.status };
        } else {
          // 更新整个订单
          const orderId = endpoint.split('/').pop();
          return { id: parseInt(orderId), ...data };
        }
      }
    }
    
    // 模拟分类相关API响应
    if (endpoint.startsWith('/categories')) {
      if (method === 'GET') {
        return this.mockCategories();
      }
    }
    
    // 模拟统计数据API响应
    if (endpoint.startsWith('/stats')) {
      if (method === 'GET') {
        return this.mockStats();
      }
    }
    
    return null;
  }
  
  // 模拟订单列表数据
  mockOrderList() {
    return [
      {
        id: 1,
        orderNumber: 'ORD-20231115-001',
        customerName: '张三',
        customerPhone: '13800138001',
        customerAddress: '北京市朝阳区建国路88号',
        orderDate: '2023-11-15T10:30:00',
        status: 'delivered',
        totalAmount: 5899,
        paymentMethod: '支付宝',
        paymentStatus: true,
        paymentDate: '2023-11-15T10:35:00',
        products: [
          { id: 2, name: '7寸穿越机', price: 3299, quantity: 1, image: 'https://picsum.photos/seed/drone1/200/200' },
          { id: 6, name: '无人机电池', price: 399, quantity: 6, image: 'https://picsum.photos/seed/battery1/200/200' }
        ]
      },
      {
        id: 2,
        orderNumber: 'ORD-20231114-002',
        customerName: '李四',
        customerPhone: '13900139002',
        customerAddress: '上海市浦东新区张江高科技园区',
        orderDate: '2023-11-14T14:20:00',
        status: 'shipped',
        totalAmount: 4599,
        paymentMethod: '微信支付',
        paymentStatus: true,
        paymentDate: '2023-11-14T14:25:00',
        products: [
          { id: 3, name: '10寸穿越机', price: 4599, quantity: 1, image: 'https://picsum.photos/seed/drone2/200/200' }
        ]
      },
      {
        id: 3,
        orderNumber: 'ORD-20231113-003',
        customerName: '王五',
        customerPhone: '13700137003',
        customerAddress: '广州市天河区天河路385号',
        orderDate: '2023-11-13T09:15:00',
        status: 'processing',
        totalAmount: 3299,
        paymentMethod: '支付宝',
        paymentStatus: true,
        paymentDate: '2023-11-13T09:20:00',
        products: [
          { id: 7, name: '遥控器', price: 1299, quantity: 1, image: 'https://picsum.photos/seed/remote1/200/200' },
          { id: 8, name: 'FPV眼镜', price: 2999, quantity: 1, image: 'https://picsum.photos/seed/goggles1/200/200' }
        ]
      },
      {
        id: 4,
        orderNumber: 'ORD-20231112-004',
        customerName: '赵六',
        customerPhone: '13600136004',
        customerAddress: '深圳市南山区科技园',
        orderDate: '2023-11-12T16:45:00',
        status: 'pending',
        totalAmount: 12999,
        paymentMethod: '银行转账',
        paymentStatus: false,
        products: [
          { id: 5, name: '工业级无人机', price: 12999, quantity: 1, image: 'https://picsum.photos/seed/industrial1/200/200' }
        ]
      },
      {
        id: 5,
        orderNumber: 'ORD-20231111-005',
        customerName: '钱七',
        customerPhone: '13500135005',
        customerAddress: '杭州市西湖区文三路',
        orderDate: '2023-11-11T20:10:00',
        status: 'canceled',
        totalAmount: 2899,
        paymentMethod: '微信支付',
        paymentStatus: true,
        paymentDate: '2023-11-11T20:15:00',
        products: [
          { id: 1, name: '5寸穿越机', price: 2899, quantity: 1, image: 'https://picsum.photos/seed/drone3/200/200' }
        ]
      },
      {
        id: 6,
        orderNumber: 'ORD-20231110-006',
        customerName: '孙八',
        customerPhone: '13400134006',
        customerAddress: '南京市鼓楼区中山路',
        orderDate: '2023-11-10T11:30:00',
        status: 'delivered',
        totalAmount: 597,
        paymentMethod: '支付宝',
        paymentStatus: true,
        paymentDate: '2023-11-10T11:35:00',
        products: [
          { id: 9, name: '备用螺旋桨', price: 129, quantity: 3, image: 'https://picsum.photos/seed/propeller1/200/200' },
          { id: 10, name: '便携收纳包', price: 499, quantity: 1, image: 'https://picsum.photos/seed/bag1/200/200' }
        ]
      },
      {
        id: 7,
        orderNumber: 'ORD-20231109-007',
        customerName: '周九',
        customerPhone: '13300133007',
        customerAddress: '成都市锦江区春熙路',
        orderDate: '2023-11-09T13:20:00',
        status: 'processing',
        totalAmount: 5899,
        paymentMethod: '微信支付',
        paymentStatus: true,
        paymentDate: '2023-11-09T13:25:00',
        products: [
          { id: 4, name: '超轻固定翼', price: 5899, quantity: 1, image: 'https://picsum.photos/seed/plane1/200/200' }
        ]
      }
    ];
  }
  
  // 模拟单个订单数据
  mockSingleOrder(id) {
    const orders = this.mockOrderList();
    return orders.find(order => order.id === id) || null;
  }
  
  // 模拟产品列表数据
  mockProductList() {
    return [
      { id: 1, name: '5寸穿越机', category: '穿越机', price: 2899, stock: 45, status: 'active', description: '高性能5寸穿越机，适合竞速和航拍', jdLink: 'https://item.jd.com/123456.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123456', douyinLink: 'https://v.douyin.com/xxxxxx', videoUrl: 'https://example.com/videos/drone1.mp4', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Drone+1+Detail'] },
      { id: 2, name: '7寸穿越机', category: '穿越机', price: 3299, stock: 32, status: 'active', description: '7寸穿越机，提供更稳定的飞行体验', jdLink: 'https://item.jd.com/123457.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123457', douyinLink: 'https://v.douyin.com/xxxxxy', videoUrl: 'https://example.com/videos/drone2.mp4', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Drone+2+Detail'] },
      { id: 3, name: '10寸穿越机', category: '穿越机', price: 4599, stock: 18, status: 'active', description: '10寸穿越机，更大尺寸带来更强动力', jdLink: 'https://item.jd.com/123458.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123458', douyinLink: 'https://v.douyin.com/xxxxxz', videoUrl: 'https://example.com/videos/drone3.mp4', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Drone+3+Detail'] },
      { id: 4, name: '超轻固定翼', category: '固定翼', price: 5899, stock: 12, status: 'active', description: '超轻固定翼无人机，适合长时间飞行任务', jdLink: 'https://item.jd.com/123459.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123459', douyinLink: 'https://v.douyin.com/xxxx00', videoUrl: 'https://example.com/videos/drone4.mp4', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Fixed+Wing'] },
      { id: 5, name: '工业级无人机', category: '工业级', price: 12999, stock: 8, status: 'active', description: '专业工业级无人机，为各行业提供解决方案', jdLink: 'https://item.jd.com/123460.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123460', douyinLink: 'https://v.douyin.com/xxxx01', videoUrl: 'https://example.com/videos/drone5.mp4', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Industrial+Drone'] },
      { id: 6, name: '无人机电池', category: '配件', price: 399, stock: 120, status: 'active', description: '高性能无人机专用电池', jdLink: 'https://item.jd.com/123461.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123461', douyinLink: 'https://v.douyin.com/xxxx02', videoUrl: '', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Battery+Detail'] },
      { id: 7, name: '遥控器', category: '配件', price: 1299, stock: 35, status: 'active', description: '专业级无人机遥控器', jdLink: 'https://item.jd.com/123462.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123462', douyinLink: 'https://v.douyin.com/xxxx03', videoUrl: 'https://example.com/videos/remote.mp4', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Remote+Control'] },
      { id: 8, name: 'FPV眼镜', category: '配件', price: 2999, stock: 20, status: 'active', description: '高清FPV飞行眼镜', jdLink: 'https://item.jd.com/123463.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123463', douyinLink: 'https://v.douyin.com/xxxx04', videoUrl: 'https://example.com/videos/goggles.mp4', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=FPV+Goggles'] },
      { id: 9, name: '备用螺旋桨', category: '配件', price: 129, stock: 200, status: 'active', description: '无人机备用螺旋桨(4个装)', jdLink: 'https://item.jd.com/123464.html', taobaoLink: 'https://detail.tmall.com/item.htm?id=123464', douyinLink: 'https://v.douyin.com/xxxx05', videoUrl: '', images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Propellers'] },
      { id: 10, name: '便携收纳包', category: '配件', price: 499, stock: 50, status: 'inactive', description: '无人机专用便携收纳包', jdLink: '', taobaoLink: '', douyinLink: '', videoUrl: '', images: [] }
    ];
  }
  
  // 模拟单个产品数据
  mockSingleProduct(id) {
    const products = this.mockProductList();
    return products.find(product => product.id === id) || null;
  }
  
  // 模拟分类数据
  mockCategories() {
    return [
      { id: 1, name: '穿越机', count: 3 },
      { id: 2, name: '固定翼', count: 1 },
      { id: 3, name: '工业级', count: 1 },
      { id: 4, name: '配件', count: 5 }
    ];
  }
  
  // 模拟统计数据
  mockStats() {
    return {
      totalProducts: 10,
      activeProducts: 9,
      inactiveProducts: 1,
      totalStock: 480,
      totalValue: 32650,
      categories: this.mockCategories()
    };
  }
  
  // 产品相关API方法
  async getProducts() {
    return this.request('GET', '/products');
  }
  
  async getProductById(id) {
    return this.request('GET', `/products/${id}`);
  }
  
  async addProduct(product) {
    return this.request('POST', '/products', product);
  }
  
  async updateProduct(id, product) {
    return this.request('PUT', `/products/${id}`, product);
  }
  
  async deleteProduct(id) {
    return this.request('DELETE', `/products/${id}`);
  }
  
  // 分类相关API方法
  async getCategories() {
    return this.request('GET', '/categories');
  }
  
  // 统计数据相关API方法
  async getStats() {
    return this.request('GET', '/stats');
  }
  
  // 上传文件（模拟）
  async uploadFile(file) {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 模拟文件上传成功，返回URL
        resolve({
          success: true,
          data: {
            url: `https://via.placeholder.com/300/4285f4/ffffff?text=${encodeURIComponent(file.name)}`
          }
        });
      }, 1000);
    });
  }
  
  // 订单相关API方法
  async getOrders() {
    return this.request('GET', '/orders');
  }
  
  async getOrderById(id) {
    return this.request('GET', `/orders/${id}`);
  }
  
  async updateOrderStatus(id, status) {
    return this.request('PUT', `/orders/${id}/status`, { status });
  }
  
  async cancelOrder(id) {
    return this.updateOrderStatus(id, 'canceled');
  }
  
  // 添加新订单
  async addOrder(order) {
    return this.request('POST', '/orders', order);
  }
  
  // 更新订单
  async updateOrder(order) {
    return this.request('PUT', `/orders/${order.id}`, order);
  }
}

// 创建单例实例
export default new ApiService();